package com.biodiv.miracle.boot.context;

import com.biodiv.miracle.boot.support.annotation.EnableAutoConfiguration;
import com.biodiv.miracle.boot.conditional.ConditionalOnMissingBeanPostProcessor;
import com.biodiv.miracle.ioc.context.ApplicationContext;
import com.biodiv.miracle.ioc.processor.BeanPostProcessor;
import com.biodiv.miracle.support.utils.AnnotationUtils;
import com.biodiv.miracle.ioc.scanner.SPIResourceLoader;
import com.biodiv.miracle.web.context.ServletWebServerApplicationContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Author: tianquan
 * @CreateTime: 2024-09-28  21:53
 * @Description: MiracleApplicationContext类快速启动类
 */
public class MiracleApplicationContext {

    /**
     * 刷新应用程序上下文的方法
     *
     * @param clazz 用于创建应用程序上下文的配置类
     * @param args  传递给应用程序的参数
     * @return 刷新后的应用程序上下文
     */
    public static ApplicationContext refresh(Class<?> clazz, String[] args) {
        // 创建容器
        ServletWebServerApplicationContext applicationContext = new ServletWebServerApplicationContext(clazz, args);
        // 判断启动类上是否有@EnableAutoConfiguration注解
        boolean isEnableAutoConfiguration = AnnotationUtils.hasClassMetaAnnotation(clazz, EnableAutoConfiguration.class);
        if (isEnableAutoConfiguration) {
            // 开启了自动装配
            Set<String> extendBeanSet = SPIResourceLoader.getClassName(EnableAutoConfiguration.class);
            if (!extendBeanSet.isEmpty()) {
                List<Class<?>> classes = SPIResourceLoader.loadClass(extendBeanSet);
                classes.forEach(applicationContext::addAutoConfigurationBeans);
            }
            // 添加BeanPostProcessor
            applicationContext.addBeanPostProcessor(new ConditionalOnMissingBeanPostProcessor());
        }
        // 刷新容器
        applicationContext.refresh();
        return applicationContext;
    }

}

